var express = require('express');
var router = express.Router();
const UserModel = require("../../models/UserModel")
const md5 = require('md5')


/* GET home page. */

router.get('/reg', (req, res, next) => {
    res.render('auth/register')
})

router.post('/reg', (req, res, next) => {
    //表单验证
    if (!(req.body.username && req.body.password)) {
        res.send('数据缺失')
        return
    }
    UserModel.findOne({ username: req.body.username })
        .then(data => {
            console.log(data)
            if (!data) {
                UserModel.create({ ...req.body, password: md5(req.body.password) })
                    .then(data => {
                        res.render('response', { url: '/login', msg: '注册成功' })
                    })
                    .catch(error => {
                        console.log(error)
                    })
            } else {
                res.send('已经被注册了')
            }
        })
        .catch(error => {
            console.log(error)
        })


})

router.get('/login', (req, res, next) => {
    console.log(req.session)
    res.render('auth/login')
})

router.post('/login', (req, res, next) => {
    //表单验证
    if (!(req.body.username && req.body.password)) {
        res.send('数据缺失')
        return
    }

    UserModel.findOne({ ...req.body, password: md5(req.body.password) })
        .then(data => {
            console.log(data)
            if (data) {
                //登录成功 设置session 跳转到主页面
                req.session.username = data.username
                req.session._id = data._id
                //以后通过_id可以找到很多东西 因为session就是用来检测登录状态 然后添加状态值的
                res.redirect('/accounts')

            }else{
                res.send('账号或者密码错误')
            }
        })
        .catch(error=>{
            console.log(error)
        })
})

router.post('/logout',(req,res,next)=>{
    req.session.destroy(()=>{
        res.render('response',{url:'/login',msg:"退出登录成功"})
    })
})



module.exports = router;
